#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItem>
#include <QStringLiteral>
#include "global.h"
#include <QDebug>
#include <QFileDialog>
#include "fileparser.h"
#include <config.h>
#include<fstream>

void MainWindow::slot_treeView_pressed(QModelIndex index)
{
    int i = 0;
    if(index.isValid())
        qDebug()<<this->mModel->itemFromIndex(index)->text();

    while(index.isValid()){
        qDebug()<<"layer"<<i<<index;
        index = index.parent();
        i++;
    }
}

MainWindow::MainWindow(QWidget *parent,float scale)
    :QssMainWindow(parent,0,scale),
      ui(new Ui::MainWindow),
      mModel(nullptr)
{
    ui->setupUi(this);
    connect(ui->configTree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(slot_treeView_pressed(QModelIndex)));

    this->setObjectName("MainWindow");
    qDebug()<<this->geometry();
    this->setGeometry(40,40,800,600);
    mInit = false;
    QObjectList list = this->children();
    ui->comboBox->addItem("yaml",QVariant("yaml"));
    ui->comboBox->addItem("json",QVariant("json"));
    ui->comboBox->addItem("xml",QVariant("xml"));

}
\

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_btnouput_clicked()
{
    if(ui->comboBox->currentText() == "json") {
        QString filepath = QFileDialog::getSaveFileName(NULL, "请选择数据文件", "", "json(*.json)");
        if (filepath.isEmpty())
        {
            QssMessageBox::warning(NULL, "提示", "未选择数据文件");
            return;
        }
        gJsonParser::Instance()->Parse(this->mModel);
        std::ofstream fout(filepath.toStdString());
        fout.close();
    }
    if(ui->comboBox->currentText() == "yaml") {
        QString filepath = QFileDialog::getSaveFileName(NULL, "请选择数据文件", "", "yaml(*.yaml)");
        if (filepath.isEmpty())
        {
            QssMessageBox::warning(NULL, "提示", "未选择数据文件");
            return;
        }
        gYamlParser::Instance()->Parse(this->mModel);
        std::ofstream fout(filepath.toStdString());
        fout << gYamlParser::Instance()->Node();
        fout.close();
    }
    if(ui->comboBox->currentText() == "xml") {
        QString filepath = QFileDialog::getSaveFileName(NULL, "请选择数据文件", "", "yaml(*.yaml)");
        if (filepath.isEmpty())
        {
            QssMessageBox::warning(NULL, "提示", "未选择数据文件");
            return;
        }
        gYamlParser::Instance()->Parse(this->mModel);
        std::ofstream fout(filepath.toStdString());
        fout.close();
    }
}

void MainWindow::on_btnimoirt_clicked()
{
        //定义文件对话框类
    QFileDialog *fileDialog = new QFileDialog(this);
       //定义文件对话框标题
    fileDialog->setWindowTitle(tr("打开配置文件"));
       //设置默认文件路径
    fileDialog->setDirectory(".");
       //设置文件过滤器
    fileDialog->setNameFilter(tr("Images(*.json *.yaml *.xml)"));
       //设置可以选择多个文件,默认为只能选择一个文件QFileDialog::ExistingFiles
    fileDialog->setFileMode(QFileDialog::ExistingFile);
       //设置视图模式
    fileDialog->setViewMode(QFileDialog::Detail);
        //打印所有选择的文件的路径
    QStringList fileNames;
    if(fileDialog->exec())
    {
        fileNames = fileDialog->selectedFiles();
        qDebug()<<fileNames;
        if(fileNames.size() != 1){
            qDebug()<<"请选择单个文件\r\n";
        }
        ui->label->setText("配置文件: " + fileNames.at(0));
        mSrcPath = fileNames.at(0);
        if(fileNames.at(0).contains(".yaml")){
            ui->comboBox->setCurrentText("yaml");
            mType = TYPE_CONFIG::TYPE_YAML;
            if (mModel != nullptr){
                ui->configTree->setModel(nullptr);
                delete mModel;
            }
            mModel = new QStandardItemModel(ui->configTree);

            connect(mModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(on_config_value_changed(QStandardItem*)));
            mModel->setHorizontalHeaderLabels(QStringList()<<"key"<<"value");
            gYamlParser::Instance()->Parse(fileNames.at(0));
            QStandardItem* item = new QStandardItem(QIcon("res/dir.svg"),QString::fromUtf8("配置"));
            gYamlParser::Instance()->Parse(fileNames.at(0));
            gYamlParser::Instance()->RenderQModelObject(item);
            mModel->appendRow(item);
            mModel->setItem(mModel->indexFromItem(item).row(),1,new QStandardItem(QString::fromUtf8("")));
            mInit =  true;
            ui->configTree->setModel(mModel);
        }
        if(fileNames.at(0).contains(".json"))
        {
            ui->comboBox->setCurrentText("json");
            if (mModel != nullptr){
                ui->configTree->setModel(nullptr);
                delete mModel;
            }
            mType = TYPE_CONFIG::TYPE_JSON;

            mModel = new QStandardItemModel(ui->configTree);
            connect(mModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(on_config_value_changed(QStandardItem*)));

            mModel->setHorizontalHeaderLabels(QStringList()<<"key"<<"value");
            QStandardItem* item = new QStandardItem(QIcon("res/dir.svg"),QString::fromUtf8("配置"));
            gJsonParser::Instance()->Parse(fileNames.at(0));
            gJsonParser::Instance()->RenderQModelObject(item);
            mModel->appendRow(item);
            item->setEditable(false);
            mModel->setItem(mModel->indexFromItem(item).row(),1,new QStandardItem(QString::fromUtf8("")));
            connect(mModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(on_config_value_changed(QStandardItem*)));
            mInit =  true;
            ui->configTree->setModel(mModel);
        }
        if(fileNames.at(0).contains(".ini"))
        {
            if (mModel != nullptr){
                ui->configTree->setModel(nullptr);
                delete mModel;
            }
            mType = TYPE_CONFIG::TYPE_INI;
            mModel = new QStandardItemModel(ui->configTree);
            mModel->setHorizontalHeaderLabels(QStringList()<<"key"<<"value");
            QStandardItem* item = new QStandardItem(QIcon("res/dir.svg"),QString::fromUtf8("配置"));
            gJsonParser::Instance()->Parse(fileNames.at(0));
            gJsonParser::Instance()->RenderQModelObject(item);
            mModel->appendRow(item);
            mModel->setItem(mModel->indexFromItem(item).row(),1,new QStandardItem(QString::fromUtf8("")));
            connect(mModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(on_config_value_changed(QStandardItem*)));
            mInit =  true;
            ui->configTree->setModel(mModel);
        }
        if(fileNames.at(0).contains(".xml"))
        {
            if (mModel != nullptr){
                ui->configTree->setModel(nullptr);
                delete mModel;
            }
            mType = TYPE_CONFIG::TYPE_XML;
            mModel = new QStandardItemModel(ui->configTree);
            mModel->setHorizontalHeaderLabels(QStringList()<<"key"<<"value");
            QStandardItem* item = new QStandardItem(QIcon("res/dir.svg"),QString::fromUtf8("配置"));
            gXmlParser::Instance()->Parse(fileNames.at(0));
            gXmlParser::Instance()->RenderQModelObject(item);
            mModel->appendRow(item);
            mInit =  true;
            ui->configTree->setModel(mModel);
        }
    }
}

void MainWindow::on_pushButton_clicked()
{

}
void ChangeJsonNode(QStringList key,YAML::Node node,QVariant x,bool ifseq){
    if(key.size() > 0){
        QString last =  key.takeLast();

    }
}
void ChangeYamlNodeConfig(QStringList key,YAML::Node node,QVariant x,bool ifseq) {
    if(key.size() > 0){
        QString last =  key.takeLast();
        for(YAML::const_iterator it= node.begin(); it != node.end();it++)
        {
            if(key.size() == 0){
                if(ifseq){
                    if(QString::fromStdString(it->as<string>()) == last){
                        node[it->as<int>()] = x.toString().toStdString();
                    }
                }else{
                    if (it->first.as<string>() == last.toStdString()){
                       (YAML::Node )(it->second) = x.toString().toStdString();
                    }
                }
            }else{
                if(it->second.Type() == YAML::NodeType::Map  ){
                    if (it->first.as<string>() == last.toStdString()){
                        qDebug()<<last;
                        ChangeYamlNodeConfig(key,it->second,x,false);
                    }
                }
                if(it->second.Type() == YAML::NodeType::Sequence){
                    if (it->first.as<string>() == last.toStdString()){
                        qDebug()<<last;
                        ChangeYamlNodeConfig(key,it->second,x,true);
                    }
                }
            }
        }
    }
}

void MainWindow::on_config_value_changed(QStandardItem *item)
{
    QStandardItem *edit = item;
    if(mInit){
        QStringList dat;
        while (item->parent() != nullptr) {
            dat.append(item->parent()->child(item->row(),0)->data(Qt::DisplayRole).toString());
            item = item->parent();
        }
        if (mType == TYPE_CONFIG::TYPE_YAML){
            YAML::Node config = gYamlParser::Instance()->Node();
            ChangeYamlNodeConfig(dat,config,edit->data(Qt::EditRole),false);
        }
        if (mType == TYPE_CONFIG::TYPE_JSON){
            YAML::Node config = gYamlParser::Instance()->Node();
            ChangeYamlNodeConfig(dat,config,edit->data(Qt::EditRole),false);
        }
    }
}

void MainWindow::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    qDebug()<<current<<previous;
}
